package thread.sync;

import thread.invariantframework.Timeout;

public class SerialNumberChecker {

	private static CircularSet serials = new CircularSet(1000);

	static class SerialChecker extends Thread {
		SerialChecker() {
			start();
		}

		@Override
		public void run() {
			while (true) {
				long serial = SerialNumberGenerator.nextSerialNumber();
				if (serials.contains(serial)) {
					System.out.println("Duplicate: " + serial);
					System.exit(0);
				}
				serials.add(serial);
			}
		}
	}

	public static void main(String[] args) {
		for (int i = 0; i < 20; i++)
			new SerialChecker();
		new Timeout(10000, "No duplicates detected");
	}
}

class CircularSet {
	private long[] array;

	private int len;

	private int index = 0;

	public CircularSet(int size) {
		array = new long[size];
		len = size;
		// Initialize to a value not produced
		// by the SerialNumberGenerator:
		for (int i = 0; i < size; i++) {
			array[i] = -1;
		}
	}

	public synchronized void add(long i) {
		array[index] = i;
		// Wrap index and write over old elements:
		index = ++index % len;
	}

	public synchronized boolean contains(long val) {
		for (int i = 0; i < len; i++) {
			if (array[i] == val)
				return true;
		}
		return false;
	}
}

class SerialNumberGenerator {
	private static long serialNumber = 0;

	public static long nextSerialNumber() {
		return serialNumber ++;
	}
}